home *** CD-ROM | disk | FTP | other *** search
- // BinarySearch.h
-
- #ifndef BinarySearch_h
- #define BinarySearch_h
-
- #ifndef Integers_h
- #include "Integers.h"
- #endif
-
- /***
- The intent here is that
-
- BinarySearch<T> search( start, gap );
- while ( search.Unfinished() )
- search.Narrow( Condition( search.Position() ) );
-
- leaves search.Position() pointing to the first
- place in start..start+gap where Condition is true,
- or start+gap if Condition is never true.
-
- For this to work, Condition must be monotonic from false
- to true as the position increases.
-
- ***/
-
- template < class IndexType >
- class BinarySearch
- {
- private:
- IndexType low;
- IndexType middle;
- uint32 gap;
-
- public:
- BinarySearch( IndexType start, uint32 theGap )
- : low( start ),
- gap( theGap ),
- middle( low + theGap / 2 )
- {}
-
- bool Finished() const { return gap == 0; }
- bool Unfinished() const { return gap > 0; }
-
- const IndexType& operator*() const { return middle; }
-
- void Narrow( bool downward )
- {
- if ( downward )
- gap = gap / 2; // gap = middle - low;
- else
- {
- gap -= (gap / 2) + 1; // gap -= middle - low + 1;
- low = middle + 1;
- }
-
- middle = low + gap/2;
- }
- };
-
- #endif
-